<template>
  <el-drawer :visible="isPop" size="60%" title="工资项" @close="onClose" custom-class="addItem" :modal="false" @open="onOpen">
    <div class="content" v-loading="loading">
      <div class="card" v-for="list in listArr.filter((item) => !item.isNoShow)" :key="list.id">
        <div class="title">
          <el-checkbox v-if="list.isCustom" v-model="list.isVisible" :indeterminate="list.indeterminate" @change="handleCheckAllChange($event, list)">
            <span style="display: flex">
              {{ list.name }}
              <div class="edit" v-if="isEdit">
                <i @click.prevent="onEditList(list)" v-if="list.isCustom" class="el-icon-edit"></i>
                <i @click.prevent="onDelList(list)" v-if="list.isCustom" class="el-icon-delete"></i>
              </div>
            </span>
          </el-checkbox>
          <span v-else>{{ list.name }}</span>
        </div>
        <div class="multiple">
          <div class="block" v-for="child in list.columnList" :key="`${child.id}-${child.name}`">
            <el-checkbox v-model="child.isVisible" :disabled="!child.isCustom && !list.isNoEdit" @change="handleCheckChange(list)">
              <span style="display: flex">
                {{ child.name }}
                <div class="edit" v-if="isEdit">
                  <i @click.prevent="onEditItem(child, list)" v-if="child.isCustom" class="el-icon-edit"></i>
                  <i @click.prevent="onDelItem(child, list)" v-if="child.isCustom" class="el-icon-delete"></i>
                </div>
              </span>
            </el-checkbox>
          </div>
          <div class="block"><el-button v-if="!list.isNoEdit" @click="onAddItem(list)">+ 自定义</el-button></div>
        </div>
      </div>
      <div class="card">
        <div class="title" style="cursor: pointer" @click="onAddGroup">+ 自定义分组</div>
      </div>
    </div>
    <div class="footer">
      <el-button v-if="!isEdit" @click="isEdit = true">编辑</el-button>
      <el-button v-else @click="isEdit = false" type="primary">完成</el-button>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认</el-button>
    </div>
    <add-item-pop :is-pop.sync="isAddPop" :group="nowList" :row.sync="nowRow" tem @affirm="onAffirm" />
    <add-group-pop :is-pop.sync="isGroupPop" :group.sync="nowList" tem @affirm="onGroupAffirm"></add-group-pop>
  </el-drawer>
</template>
<script>
import AddGroupPop from "./addGroupPop.vue";
import addItemPop from "./addItemPop.vue";
import { handleTemplateVisible } from "../../utils";
export default {
  components: { addItemPop, AddGroupPop },
  name: "addItem",
  props: {
    isPop: {
      type: Boolean,
      default: false,
    },
    lists: {
      type: Array,
      default: () => [],
    },
    isAdd: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      isAddPop: false,
      isGroupPop: false,
      nowList: "",
      nowRow: "",
      listArr: [],
      isEdit: false,
      loading: false,
    };
  },
  methods: {
    async onOpen() {
      if (this.isAdd) this.listArr = JSON.parse(JSON.stringify(this.lists));
      else if (!this.listArr.length) await this.getTemplate();
      // console.log(this.listArr);
    },
    onClose() {
      this.$emit("update:isPop", false);
    },
    // 小项相关
    ...{
      onAddItem(list) {
        this.nowList = list;
        this.nowRow = "";
        this.isAddPop = true;
      },
      onEditItem(item, list) {
        this.nowList = list;
        this.nowRow = item;
        this.isAddPop = true;
      },
      async onDelItem(child, list) {
        console.log(child, list);
        this.$confirm("确认删除吗", "提示", {}).then(async () => {
          try {
            this.loading = true;
            const { data, message = "删除成功" } = await this.$api.smartSalary.removeColumn({ id: child.id }).then((res) => res.data);
            this.$message({ message, type: "success" });
            list.columnList.splice(
              list.columnList.findIndex((item) => item.id == child.id),
              1
            );
          } finally {
            this.loading = false;
          }
        });
      },
    },
    onSubmit() {
      let newArr = this.handleItem();

      console.log(JSON.parse(JSON.stringify(this.lists)), JSON.parse(JSON.stringify(this.listArr)), newArr);
      this.$emit("submit", newArr);
      this.onClose();
    },
    // 确认数据处理
    ...{

      /** 匹配大项, 仅处理显示隐藏字段 */
      handleItem() {
        console.group("处理大项显示隐藏", this.lists, this.listArr);
        let newArr = [];
        this.listArr.forEach((item) => {
          const o = this.lists.find((list) => list.namePy == item.namePy);
          if (o) {
            newArr.push({
              ...o,
              isVisible: item.isVisible,
              columnList: this.handleChild(item.columnList, o.columnList),
            });
          } else newArr.push(JSON.parse(JSON.stringify(item)));
        });
        console.groupEnd();
        return JSON.parse(JSON.stringify(newArr));
      },

      /** 匹配小项, 仅处理显示隐藏字段 */
      handleChild(itemList, oList) {
        console.group("处理小项显示隐藏", JSON.parse(JSON.stringify(itemList)), JSON.parse(JSON.stringify(oList)));
        const newArr = itemList.map((item) => {
          const o = oList.find((list) => list.namePy == item.namePy);
          if(o) return { ...o, isVisible: item.isVisible };
          else return item;
        });
        console.log(newArr);
        console.groupEnd();
        return newArr;
      },
    },
    // 选择框
    ...{
      handleCheckAllChange(val, list) {
        this.$set(list, "indeterminate", false);
        list.columnList.forEach((item) => {
          item.isVisible = val;
        });
      },
      handleCheckChange(list) {
        if (!list.columnList.length) return;
        if (list.columnList.every((item) => item.isVisible)) {
          this.$set(list, "indeterminate", false);
          list.isVisible = true;
        } else if (list.columnList.every((item) => !item.isVisible)) {
          this.$set(list, "indeterminate", false);
          list.isVisible = false;
        } else {
          this.$set(list, "indeterminate", true);
          list.isVisible = true;
        }
      },
    },
    // 分组相关
    ...{
      onGroupAffirm(e) {
        console.log(e);
        const { edit, data } = e;
        if (edit) {
          Object.keys(data).forEach((key) => {
            if (key == "id") return;
            this.nowList[key] = data[key];
          });
        } else {
          this.listArr.push(data);
        }
        // const id = this.lists.length + 1;
        // this.lists.push({ ...e, id, name: id, columnList: [] });
        // this.active.push(id);
      },
      onAddGroup() {
        this.nowList = "";
        this.isGroupPop = true;
      },
      onEditList(list) {
        if (list.isCustom) {
          this.nowList = list;
          this.isGroupPop = true;
        }
      },
      async onDelList(list) {
        if (list.columnList.length) {
          this.$message({ message: "还有小项", type: "warning" });
        } else {
          this.$confirm("确认删除吗", "提示", {}).then(async () => {
            try {
              this.loading = true;
              const { data, message = "删除成功" } = await this.$api.smartSalary.removeItem({ id: list.id }).then((res) => res.data);
              this.$message({ message, type: "success" });
              this.listArr.splice(
                this.listArr.findIndex((item) => item.id == (data || list.id)),
                1
              );
            } finally {
              this.loading = false;
            }
          });
        }
      },
    },
    // 数据处理
    ...{

      /**
       * 获取更改数据
       * 被同步值, 参考值
       */
      getAlterData(arr = this.lists, arr1 = this.listArr) {
        const obj = this.getVisibleData(arr1);
        console.log(obj);
        let idArr = new Set([]);
        arr.forEach((item) => {
          idArr.add(item.name);
          // if(item.isCustom && !obj?.[item.name]?.isVisible) {
          //   arr.splice(i, 1);
          //   return;
          // }
          item.columnList.forEach((col) => {
            const bol = obj?.[item.name]?.columnList?.[col.name];
            if (bol) {
              if (!!col.isVisible != bol.isVisible) {
                col.isVisible = bol.isVisible;
              }
            } else col.isVisible = false;
          });
          item.isVisible = obj?.[item.name]?.isVisible;
          this.handleCheckChange(item);
        });
        // 新增项处理
        // arr1.forEach((item) => {
        //   if (!idArr.has(item.name) && item.isVisible) {
        //     arr.push({
        //       ...item,
        //       columnList: item.columnList.filter((item) => item.isVisible),
        //     });
        //   }
        // });

        console.log(obj, arr, arr1, idArr);
      },

      /**
       * 获取已勾选数据
       * @param {Array} arr 当前工作表模板数据
       * @param {Boolean} isC 是否只筛选自定义项
       */
      getVisibleData(arr = this.listArr, isC = false) {
        let obj = {};
        arr.forEach((item) => {
          let columnList = {};
          item.columnList.forEach((col) => {
            if (isC && col.isCustom || !isC) {
              if (!columnList[col.name]) columnList[col.name] = {};
              columnList[col.name].isVisible = !!col.isVisible;
            }
          });
          if (Object.keys(columnList).length) obj[item.name] = { columnList };

          if (isC && item.isCustom || !isC) {
            if (!obj[item.name]) obj[item.name] = {};
            obj[item.name].isVisible = item.isVisible;
          }
        });
        return obj;
      },
    },
    onAffirm(e) {
      console.log(e);
      const { data, edit } = e;
      if (edit) {
        Object.keys(data).forEach((key) => {
          this.nowRow[key] = data[key];
        });
      } else {
        this.nowList.columnList.push(data);
        this.handleCheckChange(this.nowList);
      }
    },
    async getTemplate() {
      try {
        this.loading = true;
        const { data } = await this.$api.smartSalary.salaryTenantPublicTemplate().then((res) => res.data);

        this.listArr = handleTemplateVisible(data);

        this.getAlterData(this.listArr, this.lists);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
:deep( .el-drawer) {
  .el-drawer__header {
    background: #f5f8fd;
    margin-bottom: 0;
    padding: 10px 20px;
    color: #000;
  }
  .el-drawer__body {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .edit {
      i {
        padding-left: 5px;
      }
    }
    .content {
      margin: 10px;
      overflow: auto !important;
    }
    .footer {
      min-height: 70px;
      display: flex;
      border-top: 1px solid #eff3f7;
      align-items: center;
      justify-content: center;
    }
    .card {
      border-bottom: 1px solid #e1e1e3;
      padding-left: 20px;
      &:last-child {
        border: none;
      }
      .title {
        position: relative;
        font-size: 15px;
        display: flex;
        align-items: center;
        align-content: center;
        padding-left: 10px;
        margin: 10px 0;
        span {
          font-weight: bold;
        }
        .el-checkbox {
          color: #000;
        }
        &::before {
          content: "";
          position: absolute;
          background: #628cfd;
          width: 3px;
          height: 14px;
          margin-top: -2px;
          left: 0;
        }
      }
      .multiple {
        margin: 10px 0;
        display: flex;
        flex-wrap: wrap;
        .block {
          margin: 10px 20px 10px 0;
        }
      }
    }
  }
}
</style>
